package org.cypress.rtpack.service;

import org.cypress.rtpack.VO.SoeRawData;
import org.cypress.rtpack.VO.SoeViewData;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

import org.cypress.rtpack.service.impl.SoeServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SoeDataConverter {
    private static final Logger logger = LoggerFactory.getLogger(SoeDataConverter.class);
    // 事件类型枚举
    public enum EventType {
        UNKNOWN(0, "未知"),
        RISE_EDGE(1, "上升沿"),
        FALL_EDGE(2, "下降沿"),
        OVERFLOW_CEILING(4, "超出上限"),
        OVERFLOW_CEILING_NORMAL(8, "超出上限恢复正常"),
        OVERFLOW_FLOOR(16, "超出下限"),
        OVERFLOW_FLOOR_NORMAL(32, "超出下限恢复正常");

        private final int code;
        private final String description;

        EventType(int code, String description) {
            this.code = code;
            this.description = description;
        }

        public static String getDescription(int code) {
            for (EventType type : values()) {
                if (type.code == code) {
                    return type.description;
                }
            }
            return UNKNOWN.description;
        }
    }

    /**
     * 转换原始数据列表为视图数据列表
     */
    public static List<SoeViewData> convert(List<SoeRawData> rawDataList) {
        return rawDataList.stream()
                .map(SoeDataConverter::convertSingle)
                .collect(Collectors.toList());
    }

    /**
     * 单条数据转换
     */
    private static SoeViewData convertSingle(SoeRawData raw) {
        SoeViewData view = new SoeViewData();

        // 时间格式化（使用unix_time1作为主时间）
        view.setTime(formatUnixTime(raw.getUnixTime1(),(raw.getUnixTime2() * 1000)));

        // 直接映射字段
        view.setChannelName(raw.getChannelName());
        view.setChannelAlias(raw.getChannelAlias());
        view.setTagName(raw.getTagName());
        view.setDescription(raw.getDescription());

        // 事件类型转换
        view.setEvent(EventType.getDescription(raw.getEventV()));

        // 值描述转换
        view.setValDes(resolveValueDescription(raw));

        return view;
    }

    /**
     * 处理值描述逻辑
     */
    private static String resolveValueDescription(SoeRawData raw) {
        // 处理event_v为1或2的情况
        if (raw.getEventV() == EventType.RISE_EDGE.code ||
                raw.getEventV() == EventType.FALL_EDGE.code) {

            logger.info("1alis=|{}|",raw.getState1Alias());
            if (raw.getVal() >= 0.5f && raw.getState1Alias() != null && !"".equals(raw.getState1Alias())) {
                logger.info("get1alis");
                return raw.getState1Alias();
            }
            if (raw.getVal() < 0.5f && raw.getState0Alias() != null && !"".equals(raw.getState0Alias())) {
                return raw.getState0Alias();
            }
        }

        // 默认情况：格式化数值（最多3位小数，不补零）
        return formatFloat(raw.getVal());
    }

    /**
     * 格式化Unix时间戳
     */
    private static String formatUnixTime(int unixTime1,int unixTime2) {
        return LocalDateTime.ofInstant(
                Instant.ofEpochSecond(unixTime1,unixTime2),
                ZoneId.systemDefault()
        ).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    /**
     * 格式化浮点数（最多3位小数，不补零）
     */
    private static String formatFloat(float value) {
        String str = String.format("%.3f", value);
        return str.replaceAll("\\.?0+$", ""); // 去除末尾多余的零和小数点
    }
}